package fr.sedoo.commons.metadata.utils.xml;

import net.jcip.annotations.Immutable;

import org.geotoolkit.util.Strings;
import org.geotoolkit.xml.Namespaces;

import com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper;

	@Immutable
	final class RBVNamespacePrefixMapper extends NamespacePrefixMapper {
	    /**
	     * If set, this namespace will be the root of the document with no prefix.
	     */
	    private final String rootNamespace;

	    /**
	     * The default prefix to return when no namespace is given.
	     */
	    private final String defaultPrefix;

	    /**
	     * Builds a mapper of prefixes.
	     *
	     * @param rootNamespace The root namespace.
	     */
	    public RBVNamespacePrefixMapper(final String rootNamespace) {
	        this.rootNamespace = rootNamespace;
	        defaultPrefix = rootNamespace.substring(rootNamespace.lastIndexOf('/') + 1);
	    }

	    /**
	     * Returns a preferred prefix for the given namespace URI.
	     *
	     * @param  namespace  The namespace URI for which the prefix needs to be found.
	     * @param  suggestion The suggested prefix, returned if the given namespace is not recognized.
	     * @param  required   Ignored in this implementation.
	     * @return The prefix inferred from the namespace URI.
	     */
	    @Override
	    public String getPreferredPrefix(String namespace, final String suggestion, final boolean required) {
	        if (namespace == null || namespace.isEmpty()) {
	            return defaultPrefix;
	        }
	        /*
	         * If the current namespace is the one defined as root namespace, this implementation
	         * just returns an empty string. This namespace will be defined with a xmlns parameter,
	         * and all tags in this namespace will not have any namespace prefix.
	         */
	        if (namespace.equals(rootNamespace)) {
	            return "";
	        }
	        if (namespace.equals(RBVNamespaces.RBV_NAMESPACE))
	        {
	        	return RBVNamespaces.RBV_PREFIX;
	        }
	        if (namespace.equals(RBVNamespaces.GMD_NAMESPACE))
	        {
	        	return RBVNamespaces.GMD_PREFIX;
	        }
	        
	        return Namespaces.getPreferredPrefix(namespace, suggestion);
	    }

	    /**
	     * Returns a list of namespace URIs that should be declared at the root element.
	     * This implementation returns an empty list.
	     *
	     * @return Namespace URIs that should be declared at the root element.
	     */
	    @Override
	    public String[] getPreDeclaredNamespaceUris() {
	        return Strings.EMPTY;
	    }

}
